package com.tingyun.sign.companyUser.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.tingyun.sign.companyUser.service.CompanyUserService;
import com.tingyun.sign.core.entity.ScActivityBean;
import com.tingyun.sign.core.entity.ScUCompanyUserBean;
import com.tingyun.sign.core.repository.ActivityDao;
import com.tingyun.sign.core.repository.CompanyUserDao;
import com.tingyun.sign.utils.DateUtils;
import com.tingyun.sign.utils.MyAssert;
import com.tingyun.sign.utils.Page;

@Service("companyUserService")
public class CompanyUserServiceImpl implements CompanyUserService {

	@PersistenceContext(name = "jpa")
	private EntityManager entityManager;
	@Autowired
	private CompanyUserDao companyUserDao;

	@Autowired
	private ActivityDao activityDao;

	/**
	 * 
	 */
	@Override
	public Integer addUsers(List<ScUCompanyUserBean> list) {
		// 校验参数
		MyAssert.isTrue(!CollectionUtils.isEmpty(list), "客户信息为空");
		// TODO 校验每条数据
		for (ScUCompanyUserBean bean : list) {
			MyAssert.notNull(bean.getUserName(), "第" + (bean.getRowNum() + 1)
					+ "行[客户名]为空");
			MyAssert.notNull(bean.getCompanyName(), "第"
					+ (bean.getRowNum() + 1) + "行[公司名]为空");
			MyAssert.notNull(bean.getActivityId(), "第" + (bean.getRowNum() + 1)
					+ "行[活动]为空");
		}
		// 保存客户信息
		try {
			companyUserDao.save(list);
		} catch (Exception e) {
			MyAssert.isTrue(false, "批量保存时发生错误，请稍后重试");
		}
		return list.size();
	}

	/**
	 * 
	 */
	@Override
	public Integer addUser(ScUCompanyUserBean bean) {
		// 校验参数
		MyAssert.notNull(bean, "客户信息为空");
		// TODO 校验每条数据
		MyAssert.notNull(bean.getUserName(), "[客户名]为空");
		MyAssert.notNull(bean.getCompanyName(), "[公司名]为空");
		MyAssert.notNull(bean.getActivityId(), "[活动]为空");
		// 保存客户信息
		try {
			companyUserDao.save(bean);
		} catch (Exception e) {
			MyAssert.isTrue(false, "保存时发生错误，请稍后重试");
		}
		return 1;
	}

	/**
	 * 逻辑删除
	 */
	@Override
	@Transactional
	public Integer deleteUser(ScUCompanyUserBean bean) {
		// 校验参数
		MyAssert.notNull(bean, "客户信息为空");
		MyAssert.notNull(bean.getId(), "[ID]为空");
		MyAssert.notNull(bean.getMuser(), "[操作人]为空");
		try {
			companyUserDao.deleteUser(bean.getId(), bean.getMuser());
		} catch (Exception e) {
			MyAssert.isTrue(false, "更新时发生错误，请稍后重试");
		}
		return 1;
	}

	/**
	 * 更新客户信息
	 */
	@Transactional
	public Integer updateUser(ScUCompanyUserBean bean) {
		MyAssert.notNull(bean.getUserName(), "[客户名]为空");
		MyAssert.notNull(bean.getCompanyName(), "[公司名]为空");
		MyAssert.notNull(bean.getActivityId(), "[活动]为空");
		Integer n = companyUserDao.updateUser(bean.getId(), bean.getUserName(),
				bean.getCompanyName(), bean.getActivityId(),
				bean.getUserLevel(), bean.getRemark(), bean.getMuser(),
				bean.getOrderType(), bean.getExpectSignTime());
		if (n == 0) {
			MyAssert.isTrue(false, "数据已被其他人操作，请刷新页面重试");
		}
		return 1;
	}

	/**
	 * 客户签到
	 */
	@Override
	@Transactional
	public Integer signIn(ScUCompanyUserBean bean) {
		MyAssert.notNull(bean.getId(), "参数[客户ID]为空");
		return companyUserDao.signIn(bean.getId(), bean.getMuser());
	}

	/**
	 * 根据活动ID分页查询客户列表 参数：活动id、用户id
	 */
	public Page<ScUCompanyUserBean> findUserPage(ScUCompanyUserBean bean) {
		// 必填参数校验
		MyAssert.notNull(bean.getActivityId(), "参数[活动ID]为空");
		// 分页查询
		Page<ScUCompanyUserBean> page = new Page<ScUCompanyUserBean>();
		CriteriaBuilder cb = entityManager.getCriteriaBuilder();
		CriteriaQuery<ScUCompanyUserBean> cq = cb
				.createQuery(ScUCompanyUserBean.class);
		Root<ScUCompanyUserBean> root = cq.from(ScUCompanyUserBean.class);
		// 整合查询条件
		List<Predicate> pres = new ArrayList<Predicate>();
		pres.add(cb.equal(root.get("activityId"), bean.getActivityId()));
		pres.add(cb.greaterThanOrEqualTo(root.<Date> get("ctime"),
				bean.getStartTime()));
		pres.add(cb.lessThan(root.<Date> get("ctime"),
				DateUtils.addDay(bean.getEndTime(), 1)));
		if (bean.getId() != null) {
			pres.add(cb.equal(root.get("id"), bean.getId()));
		}
		if (bean.getUserName() != null) {
			pres.add(cb.like(root.<String> get("userName"),
					"%" + bean.getUserName() + "%"));
		}
		if (bean.getCompanyName() != null) {
			pres.add(cb.like(root.<String> get("companyName"),
					"%" + bean.getCompanyName() + "%"));
		}
		if (bean.getStatus() != null) {
			pres.add(cb.equal(root.get("status"), bean.getStatus()));
		}
		Predicate p = cb.and(pres.toArray(new Predicate[pres.size()]));
		cq.where(p);// and
		cq.orderBy(cb.desc(root.get("id")));// 排序
		// 执行查询
		TypedQuery<ScUCompanyUserBean> query = entityManager.createQuery(cq);
		query.setFirstResult(bean.getStart());
		query.setMaxResults(bean.getPageSize());
		List<ScUCompanyUserBean> list = query.getResultList();

		// 查询活动区域
		if (list != null && list.size() > 0) {
			List<Long> acIds = new ArrayList<Long>(list.size());
			for (ScUCompanyUserBean b : list) {
				acIds.add(b.getActivityId());
			}
			List<ScActivityBean> acs = (List<ScActivityBean>) activityDao
					.findByIds(acIds);
			Map<Long, ScActivityBean> acMap = new HashMap<Long, ScActivityBean>(
					acs.size());
			for (ScActivityBean b : acs) {
				acMap.put(b.getId(), b);
			}
			for (ScUCompanyUserBean b : list) {
				if (null != acMap.get(b.getActivityId())) {
					b.setActivityTopic(acMap.get(b.getActivityId()).getTopic());
					b.setArea(acMap.get(b.getActivityId()).getArea());
				}
			}
		}

		page.setResultList(list);
		// 查询总数
		// 增加了companyUser的参数status
		page.setTotalCount(countUserPageByActivityId(bean.getActivityId(),
				bean.getStartTime(), DateUtils.addDay(bean.getEndTime(), 1),
				bean.getStatus()));
		return page;
	}

	// /**
	// * 根据活动ID分页查询客户列表
	// * 参数：活动id、用户id
	// */
	// public Page<ScUCompanyUserBean> findUserPage(ScUCompanyUserBean bean) {
	// MyAssert.notNull(bean.getActivityId(), "参数[活动ID]为空");
	// Page<ScUCompanyUserBean> page = new Page<ScUCompanyUserBean>();
	// StringBuilder sql = new StringBuilder();
	// sql.append("SELECT T FROM ScUCompanyUserBean T WHERE T.activityId=?");
	// if(bean.getUserName()!=null) {
	// sql.append("and id = ? ");
	// }
	// sql.append(" ORDER BY ID DESC");
	// // TypedQuery<ScUCompanyUserBean> query =
	// entityManager.createQuery(sb.toString(), ScUCompanyUserBean.class);
	// TypedQuery<ScUCompanyUserBean> query = (TypedQuery<ScUCompanyUserBean>)
	// entityManager.createQuery(sql.toString());
	// query.setFirstResult(bean.getStart());
	// query.setMaxResults(bean.getPageSize());
	// query.setParameter(1, bean.getActivityId());
	// List<ScUCompanyUserBean> list = query.getResultList();
	// page.setResultList(list);
	// page.setTotalCount(countUserPageByActivityId(bean.getActivityId()));
	//
	// // CriteriaQuery<ScUCompanyUserBean> cq =
	// return page;
	// }

	/**
	 * 根据活动ID查询客户总数
	 * 
	 * @param end
	 * @param start
	 *            status为空时查询全部数目
	 */
	public Integer countUserPageByActivityId(Long activityId, Date start,
			Date end, Integer status) {
		Query query = null;
		if (status == null) {
			String sql = "SELECT COUNT(ID) FROM Sc_U_Company_User T WHERE ctime >= ? and ctime < ? and T.activity_Id=?";
			query = entityManager.createNativeQuery(sql);
			query.setParameter(1, start);
			query.setParameter(2, end);
			query.setParameter(3, activityId);
		} else {
			if (status == 1 || status == 0) {
				String sql = "SELECT COUNT(ID) FROM Sc_U_Company_User T WHERE ctime >= ? and ctime < ? and T.activity_Id=? and T.status = ?";
				query = entityManager.createNativeQuery(sql);
				query.setParameter(1, start);
				query.setParameter(2, end);
				query.setParameter(3, activityId);
				query.setParameter(4, status);

			}
		}
		return Integer.parseInt(query.getSingleResult().toString());
	}
	
	/**
	 * 不包含时间的活动ID统计
	 * @param activityId
	 * @param status
	 * @param userName
	 * @return
	 */
	public Integer countUserPageByNoTimeActivityId(Long activityId, Integer status, String userName) {
		Query query = null;
		if (userName == "") {
			String sql = "SELECT COUNT(ID) FROM Sc_U_Company_User T WHERE T.activity_Id=? and T.status = ?";
			query = entityManager.createNativeQuery(sql);
			query.setParameter(1, activityId);
			query.setParameter(2, status);
		} else {
			if (userName != null) {
				String sql = "SELECT COUNT(ID) FROM Sc_U_Company_User T WHERE T.activity_Id=?  and T.status = ? and T.user_Name = ?";
				query = entityManager.createNativeQuery(sql);
				query.setParameter(1, activityId);
				query.setParameter(2, status);
				query.setParameter(3, userName);

			}
		}
		return Integer.parseInt(query.getSingleResult().toString());
	}

	@Override
	public Page<ScUCompanyUserBean> findUser(ScUCompanyUserBean bean) {
		bean.setStatus(0);
		// 必填参数校验
		MyAssert.notNull(bean.getActivityId(), "参数[活动ID]为空");
		// 分页查询
		Page<ScUCompanyUserBean> page = new Page<ScUCompanyUserBean>();
		CriteriaBuilder cb = entityManager.getCriteriaBuilder();
		CriteriaQuery<ScUCompanyUserBean> cq = cb
				.createQuery(ScUCompanyUserBean.class);
		Root<ScUCompanyUserBean> root = cq.from(ScUCompanyUserBean.class);
		// 整合查询条件
		List<Predicate> pres = new ArrayList<Predicate>();
		pres.add(cb.equal(root.get("activityId"), bean.getActivityId()));
		if (bean.getId() != null) {
			pres.add(cb.equal(root.get("id"), bean.getId()));
		}
		if (bean.getUserName() != null) {
			pres.add(cb.like(root.<String> get("userName"),
					"%" + bean.getUserName() + "%"));
		}
		if (bean.getCompanyName() != null) {
			pres.add(cb.like(root.<String> get("companyName"),
					"%" + bean.getCompanyName() + "%"));
		}
		if (bean.getStatus() != null) {
			pres.add(cb.equal(root.get("status"), bean.getStatus()));
		}
		Predicate p = cb.and(pres.toArray(new Predicate[pres.size()]));
		cq.where(p);// and
		cq.orderBy(cb.desc(root.get("id")));// 排序
		// 执行查询
		TypedQuery<ScUCompanyUserBean> query = entityManager.createQuery(cq);
		query.setFirstResult(bean.getStart());
		query.setMaxResults(bean.getPageSize());
		List<ScUCompanyUserBean> list = query.getResultList();

		// 查询活动区域
		if (list != null && list.size() > 0) {
			List<Long> acIds = new ArrayList<Long>(list.size());
			for (ScUCompanyUserBean b : list) {
				acIds.add(b.getActivityId());
			}
			List<ScActivityBean> acs = (List<ScActivityBean>) activityDao
					.findByIds(acIds);
			Map<Long, ScActivityBean> acMap = new HashMap<Long, ScActivityBean>(
					acs.size());
			for (ScActivityBean b : acs) {
				acMap.put(b.getId(), b);
			}
			for (ScUCompanyUserBean b : list) {
				if (null != acMap.get(b.getActivityId())) {
					b.setActivityTopic(acMap.get(b.getActivityId()).getTopic());
					b.setArea(acMap.get(b.getActivityId()).getArea());
				}
			}
		}

		page.setResultList(list);
		// 查询总数
		// 增加了companyUser的参数status
		page.setTotalCount(countUserPageByNoTimeActivityId(bean.getActivityId(),bean.getStatus(),bean.getUserName()));
		return page;
	}


//	查找用户
	@Override
	public ScUCompanyUserBean findCompanyUser(Long id){
		return companyUserDao.findCompanyUser(id);
	}

}
